package com.yzh.openai.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yzh.openai.domain.auth.service.AuthService;
import com.yzh.openai.domain.auth.service.IAuthService;
import com.yzh.openai.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 登录拦截器，token校验
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private static final IAuthService authService = new AuthService();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        response.setContentType("application/json;charset=utf-8");
        //放行OPTIONS请求，它是跨域检测的
        if (request.getMethod().equals("OPTIONS")) { 
            return true;
        }
        try {
            if (!authService.checkToken(token)) {
                setResponse(response);
                log.info("拦截：{}", request.getRequestURL());
                return false;
            }
            return true;
        } catch (Exception e) {
            setResponse(response);
            log.info("拦截：{}", request.getRequestURL());
            return false;
        }
    }
    private void setResponse(HttpServletResponse response) throws IOException {
        JSONObject json = new JSONObject();
        json.put("code", Constants.ResponseCode.TOKEN_ERROR.getCode()); 
        json.put("info", Constants.ResponseCode.TOKEN_ERROR.getInfo()); 
        
        response.setStatus(HttpStatus.UNAUTHORIZED.value());    //设置响应状态401
        response.getWriter().write(json.toJSONString());

    }
}
